

import opencvUtils
import  MyUtils

import cv2
import os


def split_image(image_path,grid_w,grid_h, x_overlap=0, y_overlap=0, savePath=""):
    # 读取图像
    image = cv2.imread(image_path)
    if image is None:
        print(f"无法读取图像: {image_path}")
        return

    # 获取图像的高度和宽度
    height, width = image.shape[:2]

    # 从图像路径中提取图像名（不包含扩展名）
    image_name = os.path.splitext(os.path.basename(image_path))[0]

    # 创建以图像名命名的文件夹
    output_folder = os.path.join(savePath, image_name)
    if os.path.exists(output_folder):
        MyUtils.deleteDir(output_folder)
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 划分图像为 300x300 的小图
    step_x = grid_w - x_overlap
    step_y = grid_h - y_overlap

    for y in range(0, height, step_y):
        for x in range(0, width, step_x):
            # 计算小图的边界
            y_end = min(y + grid_h, height)
            x_end = min(x + grid_w, width)

            # 提取小图
            patch = image[y:y_end, x:x_end]

            # 检查小图是否为空
            if patch.size > 0:
                # 生成小图的文件名
                patch_name = f"{image_name}_{y}_{x}.jpg"
                patch_path = os.path.join(output_folder, patch_name)

                # 保存小图
                cv2.imwrite(patch_path, patch)
                print(f"保存小图: {patch_path}")


if __name__ == "__main__":
    # 替换为你的图像路径
    image_path = "E:\\workspace\\z-deepLearning\\Images\\1.png"
    savePath = "E:\\workspace\\z-deepLearning\\Images\\"
    split_image(image_path,grid_w=600,grid_h=600, x_overlap=100,y_overlap=100,savePath=savePath)

    exit(0)